window.addEventListener('load', function () {
    // 1. 获取元素
    var arrow_l = document.querySelector('.arrow-l');
    var arrow_r = document.querySelector('.arrow-r');
    var box = document.querySelector('.box');
    //2.经过显示隐藏左右按钮
    box.addEventListener('mouseenter', function() {
        arrow_l.style.display = 'block';
        arrow_r.style.display = 'block';
        clearInterval(timer);
        timer = null; //清除定时器变量
    });
    box.addEventListener('mouseleave', function() {
        arrow_l.style.display = 'none';
        arrow_r.style.display = 'none';
        timer = setInterval(function(){
            //手动调用点击事件
            arrow_r.click();
        },2000)
    });

    //3.动态生成小圆圈、
    var ol = document.querySelector('.circle');
    var ul = document.querySelector('ul');
    var boxWidth = box.offsetWidth;
    for(var i = 0; i < ul.children.length;i++){
        //创建小li
        var li = document.createElement('li');
        li.setAttribute('index', i);
        ol.append(li);
        //4.小圆圈的排他思想，直接为小圆圈绑定点击事件
        li.addEventListener('click',function() {
            for(var i = 0; i < ol.children.length; i++) {
                ol.children[i].className = '';
            }
            this.className = 'current';
            //5.点击小圆圈，让图片随着滚动
            //移动距离: 索引号*图片宽度
            var index = this.getAttribute('index');
            //当我们点击了某个小li，就把当前li索引号给num
            num = index;
            circle = index;
            console.log(index);
            // console.log(ulWidth);
            animate(ul, -index * boxWidth);
        })
    }
    ol.children[0].className = 'current';
    //6.克隆第一张图片放在ul最后面，实现无缝滚动的需要
    var first = ul.children[0].cloneNode(true);
    ul.append(first);

    //7.点击右侧按钮，让图片滚动一张
    var num = 0;
    var circle = 0;
    arrow_r.addEventListener('click', function() {
        if(num == ul.children.length - 1) {
            ul.style.left = 0;
            num = 0;
        }
        num++;
        animate(ul, -num * boxWidth);
        //控制小圆圈
        circle++;
        if(circle == ul.children.length - 1) {
            circle = 0;
        }
        for(var i = 0; i < ol.children.length; i++) {
            ol.children[i].className = '';
        }
        ol.children[circle].className = 'current';
    });

    //8.左侧按钮
    arrow_l.addEventListener('click', function() {
        if(num == 0) {
            num = ul.children.length - 1;
            ul.style.left = -num * boxWidth + 'px';
        }
        num--;
        animate(ul, -num * boxWidth);
        //控制小圆圈
        circle--;
        if(circle < 0) {
            circle = ol.children.length - 1;
        }
        for(var i = 0; i < ol.children.length; i++) {
            ol.children[i].className = '';
        }
        ol.children[circle].className = 'current';
    })

    //9.自动播放定时器
    var timer = setInterval(function(){
        //手动调用点击事件
        arrow_r.click();
    },2000)
})